<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 16:00
 */

namespace app\api\controller\android\v12;


use think\Cache;
use think\Controller;
use app\api\model\Authority;
use think\db;
use think\Request;
use app\api\model\OrderModel;
use think\Exception;

class User extends Controller
{
    protected $model;
    protected $us;

    public function _initialize()
    {
        $this->model = new Authority();
        $this->us    = $this->model->check(1);
    }

    /**
     * 修改手机号
     */
    public function reset_mobile()
    {
        $data = $this->model->post(['code', 'new_mobile']);
        if (!is_mobile($data['new_mobile'])) {
            r_date([], 300, '请输入正确的手机号');
        }
        $s_verify = Cache::get(md5($data['new_mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date([], 300, '验证码错误');
        }
        Cache::clear(md5($data['new_mobile']));
        $user = self::$user;
        if (db('user')->where(['mobile' => $data['new_mobile'], 'status' => ['in', '0,1,2']])->find()) {
            r_date([], 300, '该手机号已注册用户端，请重新选择手机号');
        }
        $res = db('user')->where(['user_id' => $user['user_id']])->update(['mobile' => $data['new_mobile']]);
        if ($res !== false) {
            r_date();
        }
        r_date([], 300, '修改失败，请刷新后重试');
    }

    public function index(OrderModel $orderModel)
    {
        $retrun    = db('user')->join('store st', 'st.store_id=user.store_id', 'left')->field('user.user_id,user.work_tag,user.mobile,user.username,user.avatar,user.sex,user.state,st.store_name,st.store_id,user.number,user.reserve')->where(['user_id' => $this->us['user_id']])->find();
        $BeginDate = date('Y-m-01', strtotime(2021 - 12 - 03));
        $starttime = strtotime($BeginDate);
        $enttime   = strtotime(date('Y-m-d', strtotime("$BeginDate +1 month -1 day")));
        $quantity  = db('order')->where(['created_time' => ['between', [$starttime, $enttime]], 'assignor' => $this->us['user_id']])->select();//本月接单量


        $list = $m = $orderModel->table('order')->alias('a')->field('concat(p.province,c.city,u.county,a.addres) as  addres,a.contacts,co.con_time,a.order_id,a.state,a.assignor,go.title')->join('province p', 'a.province_id=p.province_id', 'left')->join('city c', 'a.city_id=c.city_id', 'left')->join('county u', 'a.county_id=u.county_id', 'left')->join('user us', 'a.assignor=us.user_id', 'left')->join('goods_category go', 'a.pro_id=go.id', 'left')->join('contract co', 'a.order_id=co.orders_id', 'left')->where('a.assignor', $this->us['user_id'])->whereBetween('co.con_time', [$starttime, $enttime])->order('co.con_time desc')->whereBetween('a.state', [4, 7])->select();
        foreach ($list as $k => $key) {
            $mouth = $orderModel->offer($key['order_id']);
            //签约金额
            $list[$k]['amount'] = sprintf('%.2f', $mouth['amount']);
        }

        $amount = sprintf('%.2f', array_sum(array_column($list, 'amount')));

        $zeng = array_sum(array_column((new Financial)->zeng($starttime, $enttime, $this->us['user_id']), 'turnover'));

        $jian = array_sum(array_column((new Financial)->jian($starttime, $enttime, $this->us['user_id']), 'turnover'));
        $tui  = array_sum(array_column((new Financial)->tui($starttime, $enttime, $this->us['user_id']), 'turnover'));

        $ye                 = sprintf('%.2f', $amount + $zeng - $jian - $tui);
        $retrun['quantity'] = count($quantity);
        $retrun['signing']  = $ye;
        $retrun['volume']   = (new Financial)->TurnoverRate('ss');
        $retrun['bankCard'] = \db('bank_card')->where(['user_id' => $this->us['user_id'], 'binding_uid' => $this->us['user_id']])->where('category', 1)->value('bank_card_number');

        $work_tag = empty($retrun['work_tag']) ? [0, 0, 0, 0] : explode(',', $retrun['work_tag']);
        foreach ($work_tag as $k => $value) {
            $k = $k + 1;
            switch ($value) {
                case 0:
                    $value = 'https://images.yiniao.co/Icon/shopowner/small/' . $k . '-grey-small.png';
                    break;
                case 1:
                    $value = 'https://images.yiniao.co/Icon/shopowner/small/' . $k . '-small.png';
                    break;
            }
            $date[] = $value;
        }
        $retrun['work_tag'] = $date;
        $retrun['pending']  = db('direct_order', config('database.zong'))->where('user_id', $this->us['user_id'])->where('type', 1)->where('state', 0)->count();
        if ($this->us['show_ranking'] == 1) {
            $profit      = (new WorkBench())->Ranking(4, 2);
            $achievement = (new WorkBench())->Ranking(1, 2);
            $conversion  = (new WorkBench())->Ranking(2, 2);
            $repurchase  = (new WorkBench())->Ranking(3, 2);

            $retrun['profit']      = array_merge(arrayFilterFieldValue($profit, 'username', $this->us['username']))[0]['xu'] . "/" . count($profit);
            $retrun['achievement'] = array_merge(arrayFilterFieldValue($achievement, 'username', $this->us['username']))[0]['xu'] . "/" . count($achievement);
            $retrun['conversion']  = array_merge(arrayFilterFieldValue($conversion, 'username', $this->us['username']))[0]['xu'] . "/" . count($conversion);
            $retrun['repurchase']  = array_merge(arrayFilterFieldValue($repurchase, 'username', $this->us['username']))[0]['xu'] . "/" . count($repurchase);
        } else {
            $retrun['profit']      = "-/-";
            $retrun['achievement'] = "-/-";
            $retrun['conversion']  = "-/-";
            $retrun['repurchase']  = "-/-";

        }
        r_date($retrun, 200, '获取成功');
    }

    public function Icon()
    {
        $work_tag = db('user')->where(['user_id' => $this->us['user_id']])->value('work_tag');
        $work_tag = empty($work_tag) ? [0, 0, 0, 0] : explode(',', $work_tag);
        foreach ($work_tag as $k => $value) {

            switch ($k) {
                case 0:
                    $data['title'] = '建筑渗漏水维修专家';
                    break;
                case 1:
                    $data['title'] = '旧房改造类专家';
                    break;
                case 2:
                    $data['title'] = '墙面维修专家';
                    break;
                case 3:
                    $data['title'] = '室内渗漏水维修专家';
                    break;
            }
            $k = $k + 1;
            switch ($value) {
                case 0:
                    $data['img'] = 'https://images.yiniao.co/Icon/shopowner/big/' . $k . '-grey.png';
                    break;
                case 1:
                    $data['img'] = 'https://images.yiniao.co/Icon/shopowner/big/' . $k . '.png';
                    break;
            }
            $date[] = $data;
        }


        r_date($date, 200, '获取成功');
    }

    /**
     * 修改我的状态
     */
    public function state()
    {
        $data = $this->model->post(['state']);
        //店长在线时长统计
        db('online')->insertGetId(['user_id' => $this->us['user_id'], 'startTime' => time(), 'type' => $data['state'], 'time' => time()]);

        $res = db('user')->where(['user_id' => $this->us['user_id']])->update(['state' => $data['state']]);

        if ($res) {
            r_date([], 200);
        }
        r_date([], 300, '状态修改失败，请刷新后重试');
    }

    /**
     * 修改我的状态
     */
    public function switchUser()
    {
        $retrun = db('user')->field('user.user_id,user.mobile,user.username,user.avatar,user.sex,user.access_token,st.store_name,user.reserve')->join('store st', 'user.store_id=st.store_id', 'left')->where(['user.mobile' => $this->us['mobile']])->select();

        r_date($retrun, 200);
    }

    /**
     * 修改资料
     * invoice_type
     */
    public function edit()
    {
        $data = $this->model->post(['avatar']);
        $res  = db('user')->where(['user_id' => $this->us['user_id']])->update(['avatar' => $data['avatar'],]);
        if ($res !== false) {
            r_date([], 200);
        }
        r_date([], 300, '编辑失败，请刷新后重试');
    }


    public function Article()
    {
        $result = send_post(U_SRC . "/support/v1.article/all", []);


        return r_date(json_decode($result, true), 200);
    }

    public function Article_list()
    {
        $data   = $this->model->post(['category_id', 'limit', 'page']);
        $result = send_post(U_SRC . "/support/v1.article/lists", $data);

        return r_date(json_decode($result, true), 200);
    }

    /*
     * 免打扰
     */
    public function disturb()
    {
        $this->model->post(['type']);
        db('user')->where('user_id', $this->us['user_id'])->update(['disturb' => 2]);
        r_date([], 200);
    }

    /*
     * 获取地理位置
     */
    public function lat()
    {
        $data = $this->model->post(['lat', 'lng']);
        db('user')->where('user_id', $this->us['user_id'])->update(['lat' => $data['lat'], 'lng' => $data['lng']]);
        r_date(null, 200);
    }

    /*
     * 免打扰
     */
    public function about()
    {
        $da = db('about')->find();
        r_date($da, 200);
    }

    public function url()
    {
        $da['url'] = 'http://public.yiniaoweb.com/static/help/storemanage/';
        r_date($da, 200);
    }

    /*
     * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
     * 30  费用报销 31 主材费用报销，32返工费用报销 33 常规材料  34 采购材料  35 领用申请
     */
    public function message()
    {

        $message = db('message')->field('type,content,order_id,already,id')->where(['user_id' => $this->us['user_id']])->limit(0, 3)->orderRaw('already=1 desc,time desc')->select();
        $data    = [
            'data' => $message,
            'newOrders' => db('message')->where(['user_id' => $this->us['user_id'], 'type' => ['in', '2,3,4,6,45'], 'already' => 1])->count(),// 订单提醒
            'approval' => db('message')->where(['user_id' => $this->us['user_id'], 'type' => ['in', '30,31,32,33,34,35'], 'already' => 1])->count(),// 审批提醒
//                  'Material'=>db('message')->where(['type'=>['in', '34,33'],'already'=>1, 'user_id'=>$this->us['user_id']])->count(),//
            'system' => db('message')->where(['type' => 1, 'already' => 1, 'user_id' => $this->us['user_id']])->count(),//系统消息
            'unread' => db('message')->where(['user_id' => $this->us['user_id'], 'already' => 1])->count(),//未读消息

        ];
        r_date($data, 200);
    }

    /*
    * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
    */
    public function message_list()
    {
        //0全部1系统2订单3收款5公司通知7未读
        $data = $this->model->post(['type', 'page' => 1, 'limit' => 10, 'title']);
        $me   = db('message');
        if (isset($data['title']) && $data['title'] != '') {
            $map['content'] = ['like', "%{$data['title']}%"];
            $me->where($map);
        }
        if ($data['type'] == 2) {
            $me->where(['type' => ['in', '3,4,6,45']]);
        } elseif ($data['type'] == 7) {
            $me->where(['already' => 1]);
        } elseif ($data['type'] == 5) {
            $me->where(['type' => $data['type']]);
        } elseif ($data['type'] == 1) {
            $me->where(['type' => $data['type']]);
        } elseif ($data['type'] == 22) {
            $me->where(['type' => ['in', '30,31,32']]);
        } elseif ($data['type'] == 23) {
            $me->where(['type' => ['in', '33,34,35,36,37']]);
        }
        $message = $me->where(['user_id' => $this->us['user_id']])->field('id,type,content,order_id,already')->orderRaw('already=1 desc,time desc')->page($data['page'], $data['limit'])->select();
        r_date($message, 200);
    }

    /*
     * 审批里面的类型
     */
    public function ApprovalType()
    {
        $data = $this->model->post(['type']);
        if ($data['type'] == 2) {
            $data = [
                [
                    'name' => '全部',
                    'type' => 0,
                    'jump' => 0,
                ],
                [
                    'name' => '订单提醒',
                    'type' => 2,
                    'jump' => 0,
                ], [
                    'name' => '收款预警提醒',
                    'type' => 45,
                    'jump' => 0,
                ]
            ];
        } else {
            $data = [
                [
                    'name' => '全部',
                    'type' => 0,
                    'jump' => 0,
                ], [
                    'name' => '费用报销',
                    'type' => 30,
                    'jump' => 0,
                ], [
                    'name' => '主材费用报销',
                    'type' => 31,
                    'jump' => 0,
                ], [
                    'name' => '材料常规申请（常规）',
                    'type' => 33,
                    'jump' => 0,
                ], [
                    'name' => '返工费用报销',
                    'type' => 32,
                    'jump' => 0,
                ], [
                    'name' => '材料申请（采购）',
                    'type' => 34,
                    'jump' => 0,
                ], [
                    'name' => '材料领用',
                    'type' => 35,
                    'jump' => 0,
                ],[
                    'name' => '退款消息',
                    'type' => 37,
                    'jump' => 0,
                ],[
                    'name' => '大工地审批',
                    'type' => 36,
                    'jump' => 0,
                ]

            ];
        }
        r_date($data, 200);
    }

    /*
   * /**30  费用报销 31 主材费用报销，32返工费用报销 33 常规材料  34 采购材料
     * 费用报销内容
     */

    public function message_listApproval()
    {

        $data = $this->model->post(['type', 'mainType', 'page', 'limit']);

        $me = db('message');
        if (isset($data['title']) && $data['title'] != '') {
            $map['content'] = ['like', "%{$data['title']}%"];
            $me->where($map);
        }
        if ($data['mainType'] == 2) {
            if ($data['type'] != 0) {
                if ($data['type'] == 2) {
                    $me->where(['type' => ['in', '3,4,6']]);
                } else {
                    $me->where(['type' => $data['type']]);
                }

            } else {
                $me->whereIn('type', [3, 4, 6, 2, 45]);
            }
        } else {
            if ($data['type'] != 0) {
                $me->where(['type' => $data['type']]);
            } else {
                $me->whereIn('type', [30, 31, 32, 33, 34, 35]);
            }
        }

        $message = $me->where(['user_id' => $this->us['user_id']])->field('id,type,content,order_id,already,FROM_UNIXTIME(time,"%Y-%m-%d %H:%i:%s")')->orderRaw('already=1 desc,time desc')->page($data['page'], $data['limit'])->select();
        foreach ($message as $k => $value) {
            if (!empty($value['order_id']) && $value['type'] == 45) {
                $order = db('order')
                    ->field('order.contacts,order.telephone,concat(p.province,c.city,y.county,order.addres) as addres,sum(payment.material+payment.agency_material) as sum,count(payment_id) as count')
                    ->join('user u', 'order.assignor=u.user_id', 'left')
                    ->join('province p', 'order.province_id=p.province_id', 'left')
                    ->join('city c', 'order.city_id=c.city_id', 'left')
                    ->join('county y', 'order.county_id=y.county_id', 'left')
                    ->join('payment', 'order.order_id=payment.orders_id and payment.cleared_time >0', 'left')
                    ->where('order.order_id', $value['order_id'])
                    ->find();

                $order['collection'] = $money = OrderModel::offer($value['order_id'])['amount'];
            } else {
                $order = null;
            }
            $message[$k]['order'] = $order;
        }
        r_date($message, 200);
    }

    /*
    * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
    */
    public function message_info()
    {
        $data            = $this->model->post(['id']);
        $message         = db('message')->where('id', $data['id'])->field('type,content,order_id,already,time')->find();
        $message['time'] = date('Y-m-d H:i:s', $message['time']);
        if ($message['already'] != 0) {
            db('message')->where('id', $data['id'])->update(['already' => 0, 'have' => time()]);
        }

        r_date($message, 200);
    }

    /*
     * 储备店长
     */
    public function reserve()
    {
        $data   = $this->model->post();
        $chanel = db('user')->field('user.number,user.username,user.mobile,user.lat,user.lng,user.user_id');
        if (isset($data['username']) && $data['username'] != '') {
            $chanel->where(['user.username' => ['like', "%{$data['username']}%"]]);
        }
        $list = $chanel->where(['status' => 0, 'reserve' => 2, 'store_id' => $this->us['store_id']])->order('status')->select();
        r_date($list, 200);
    }

    /**
     * 获取后台客户注册的
     */
    public function jp()
    {
        $message = db('admin')->field('username,logo,admin_id')->where(['status' => 0, 'jp' => 1])->select();
        r_date($message, 200);
    }

    /**
     * 店铺
     * invoice_type
     */
    public function store()
    {
        $res = db('store')->field('store_id,store_name')->select();

        r_date($res, 200);


    }

    /**
     *工种
     * invoice_type
     */
    public function workType()
    {
        $res = Db::connect(config('database.db2'))->table('app_work_type')->whereNull('deleted_at')->where('status', 1)->field('id,title')->select();

        r_date($res, 200);
    }

    /*
     * 银行卡添加
     */
    public function bankCard()
    {

        $bank_card = \db('bank_card')->where('bank_card.delete_time', 0)->where(['user_id' => $this->us['user_id'], 'binding_uid' => $this->us['user_id']])->where('category', 1)->field('bank_card_number as bankCardNumber,account_name as accountName,bank_of_deposit as bankOfDeposit,bank_id as bankId,bank')->find();
        if (empty($bank_card)) {
            $list = ['bankCardNumber' => '', 'bankOfDeposit' => '', 'bankId' => (int)0, 'accountName' => ''];
        } else {
            $list = $bank_card;
        }
        r_date($list, 200);
    }

    public function addBankCard()
    {
        $data = Request::instance()->post();

//        if (!check_bankCard($data['bankCardNumber'])) {
//            r_date(null, 300, '请输入正确的银行卡号');
//        }
        $count = db('bank_card')->where('bank_card.delete_time', 0)->where(['bank_card_number' => $data['bankCardNumber']])->count();
        if ($count > 0) {
            r_date(null, 300, '请勿重复录入');
        }
        if (isset($data['id']) && !empty($data['id']) != 0) {
            $res = db('bank_card')->where('bank_id', $data['id'])->where('category', 1)->update(['account_name' => $data['accountName'], 'bank_card_number' => $data['bankCardNumber'], 'bank_of_deposit' => $data['bankOfDeposit'], 'bank' => $data['bank'], 'revision_time' => time()]);
        } else {

            $res = db('bank_card')->insertGetId(['user_id' => $this->us['user_id'], 'account_name' => $data['accountName'], 'bank_card_number' => $data['bankCardNumber'], 'bank_of_deposit' => $data['bankOfDeposit'], 'type' => 2, 'creation_time' => time(), 'category' => 1, 'remarks' => '店长', 'binding_uid' => $this->us['user_id'], 'bank' => $data['bank']]);
        }
        if ($res) {
            r_date($data['bankCardNumber'], 200);
        } else {
            r_date(null, 300);
        }
    }

    public function collectionOtherAdd()
    {
        $data  = Request::instance()->post();
        $count = db('bank_card')->where('bank_card.delete_time', 0)->where(['bank_card_number' => $data['bankCardNumber']])->count();
        if ($count > 0) {
            r_date(null, 300, '请勿重复录入');
        }
        //        if (!check_bankCard($data['bankCardNumber'])) {
        //            r_date(null, 300, '请输入正确的银行卡号');
        //        }

        $res = db('bank_card')->insertGetId(['user_id' => $this->us['user_id'], 'account_name' => $data['accountName'], 'bank_card_number' => $data['bankCardNumber'], 'bank_of_deposit' => $data['bankOfDeposit'], 'type' => $data['type'], 'creation_time' => time(), 'category' => 1, 'remarks' => $data['remarks'], 'bank' => $data['bank']]);

        if ($res) {
            $data['bankId'] = $res;
            r_date($data, 200);
        } else {
            r_date(null, 300);
        }
    }

    /*
     * val bankCardNumber: String?,
val accountName: String?,
val bankOfDeposit: String?,
val remarks: String?,
val type: String?,
val bankId: Int?
     */
    public function searchBank()
    {
        $data = Request::instance()->post();
        $res  = db('bank_card')->where(function ($query) use ($data) {
            if ($data['accountName'] != '') {
                $query->whereOr('bank_card_number', 'Like', "%{$data['accountName']}%")->whereOr('account_name', 'Like', "%{$data['accountName']}%");
            }

        })->where('delete_time', 0)->field('bank_card_number as bankCardNumber,account_name as accountName,bank_of_deposit as bankOfDeposit,bank_id as bankId,remarks')->select();

        r_date($res, 200);

    }

    /*
     * 最近使用的
     */
    public function searchLatelBank()
    {

        $res = db('reimbursement_relation')
            ->join('reimbursement', 'reimbursement_relation.reimbursement_id=reimbursement.id', 'left')
            ->Join('bank_card', 'bank_card.bank_id=reimbursement_relation.bank_id', 'left')
            ->where('reimbursement.user_id', $this->us['user_id'])
            ->where('reimbursement.type', 1)
            ->where('bank_card.delete_time', 0)
            ->where('reimbursement.classification', 'neq', 4)
            ->field('bank_card.bank_card_number as bankCardNumber,bank_card.remarks,bank_card.account_name as accountName,bank_card.bank_of_deposit as bankOfDeposit,bank_card.bank_id as bankId')
            ->limit(0, 3)
            ->group('bank_card.bank_card_number')
            ->order('reimbursement.id desc')
            ->select();
        r_date($res, 200);

    }

    /*
     * 联系人标签
     */

    public function contactLabel()
    {
        $data           = Authority::param(['order_id']);
        $telephone = db('order')->where('order_id', $data['order_id'])->value('telephone');
        $labelList      = db('contact_label', config('database.zong'))->field('contacts_id,title,content,option')->where('status', 1)->select();
        $orderLabelList = db('order_contact_label', config('database.zong'))->where('telephone', $telephone)->whereNull('delete_time')->field('classification,order_id,contact_label')->select();
        $result         = array();
        $schemeTag      = array();
        foreach ($labelList as $k => $v) {
            $labelList[$k]['choice'] = 0;
            foreach ($orderLabelList as $item) {
                if ($v['contacts_id'] == $item['contact_label']) {
                    $labelList[$k]['choice'] = 1;
                }
            }

        }
        foreach ($labelList as $k => $v) {
            $result[$v['title']][] = $v;
        }
        foreach ($result as $k => $list) {
            $schemeTag['title']  = $k;
            $schemeTag['id']     = $list[0]['contacts_id'];
            $schemeTag['option'] = $list[0]['option'];
            $schemeTag['data']   = $result[$k];
            $tageList[]          = $schemeTag;
        }
        r_date(['labelList' => $tageList, 'orderLabelList' => $orderLabelList], 200);
    }


    public function contactLabelEdit()
    {
        $data                           = Authority::param(['contactLabelArray', 'order_id']);
        $contactLabelArray              = json_decode($data['contactLabelArray'], true);
        $contactLabelArrayOriginal      = [];
        $contactLabelArrayList          = [];
        $contactLabelArrayListCancelled = [];
        $alreadyCancelled               = [];
        $alreadyCancelledADD            = [];
        db()->startTrans();
        try {
            $telephone = db('order')->where('order_id', $data['order_id'])->value('telephone');
            foreach ($contactLabelArray as $list) {
                foreach ($list['data'] as $item) {
                    if ($item['isMyChoice'] == 0 && $item['choice'] == 1) {
                        //原来的
                        $contactLabelArrayOriginal[] = $item;
                    }
                    if ($item['isMyChoice'] == 1 && $item['choice'] == 0) {
                        //新增的
                        $contactLabelArrayList[] = $item;
                    }
                    if ($item['isCancel'] == 1 && $item['choice'] == 1) {
                        //新增的
                        $contactLabelArrayListCancelled[] = $item;
                    }

                }

            }
            $already = [];
            foreach ($contactLabelArrayOriginal as $item) {
                foreach ($contactLabelArrayList as $value) {
                    if ($item['title'] == $value['title']) {
                        $opList['order_id']     = $data['order_id'];
                        $opList['created_time'] = time();
                        $opList['content']      = $item['title'] . $item['content'] . '标记为:' . $value['content'];
                        $opList['operation']    = $this->us['username'];
                        $opList['user_id']      = $this->us['user_id'];
                        $contact_label[]        = $item['contacts_id'];
                        $opList['role']         = 1;
                        $already[]              = $opList;
                    }
                }

            }
            foreach ($contactLabelArrayListCancelled as $l) {
                if (!empty($contactLabelArrayList)) {
                    foreach ($contactLabelArrayList as $value) {
                        if ($l['title'] != $value['title']) {

                            $opListCancelled['order_id']     = $data['order_id'];
                            $opListCancelled['created_time'] = time();
                            $opListCancelled['content']      = $l['title'] . '取消了：' . $l['content'];
                            $opListCancelled['operation']    = $this->us['username'];
                            $opListCancelled['user_id']      = $this->us['user_id'];
                            $contact_labelList[]             = $l['title'];
                            $contact_labelListID[]           = $l['contacts_id'];
                            $opListCancelled['role']         = 1;
                            $alreadyCancelled[]              = $opListCancelled;

                        }
                    }

                } else {
                    $opListCancelled['order_id']     = $data['order_id'];
                    $opListCancelled['created_time'] = time();
                    $opListCancelled['content']      = $l['title'] . '取消了：' . $l['content'];
                    $opListCancelled['operation']    = $this->us['username'];
                    $opListCancelled['user_id']      = $this->us['user_id'];
                    $contact_labelList[]             = $l['title'];
                    $contact_labelListID[]           = $l['contacts_id'];
                    $opListCancelled['role']         = 1;
                    $alreadyCancelled[]              = $opListCancelled;
                }


            }
            $listArrayNew = [];
            foreach ($contactLabelArrayList as $item) {

                $listArray['order_id']       = $data['order_id'];
                $listArray['contact_name']   = $item['title'];
                $listArray['contact_label']  = $item['contacts_id'];
                $listArray['role']           = 1;
                $listArray['user_id']        = $this->us['user_id'];
                $listArray['created_time']   = time();
                $listArray['classification'] = $item['content'];
                $listArray['telephone'] = $telephone;
                $listArrayNew[]              = $listArray;
                if (!empty($contactLabelArrayOriginal)) {
                    foreach ($contactLabelArrayOriginal as $value) {
                        if ($item['title'] != $value['title']) {
                            $opListCancelledADD['order_id']     = $data['order_id'];
                            $opListCancelledADD['created_time'] = time();
                            $opListCancelledADD['content']      = $item['title'] . '标记为:' . $item['content'];
                            $opListCancelledADD['operation']    = $this->us['username'];
                            $opListCancelledADD['user_id']      = $this->us['user_id'];
                            $opListCancelledADD['role']         = 1;
                            $alreadyCancelledADD[]              = $opListCancelledADD;
                        }}

                } else {
                    $opListCancelledADD['order_id']     = $data['order_id'];
                    $opListCancelledADD['created_time'] = time();
                    $opListCancelledADD['content']      = $item['title'] . '标记为:' . $item['content'];
                    $opListCancelledADD['operation']    = $this->us['username'];
                    $opListCancelledADD['user_id']      = $this->us['user_id'];
                    $opListCancelledADD['role']         = 1;
                    $alreadyCancelledADD[]              = $opListCancelledADD;
                }


            }

            if (!empty($already)) {
                db('order_contact_label_logo', config('database.zong'))->insertAll($already);
                db('order_contact_label', config('database.zong'))->where('order_id', $data['order_id'])->whereIn('contact_label', array_unique($contact_label))->update(['delete_time' => time()]);

            }
            if (!empty($alreadyCancelled)) {
                db('order_contact_label_logo', config('database.zong'))->insertAll($alreadyCancelled);
                db('order_contact_label', config('database.zong'))->where('order_id', $data['order_id'])->whereIn('contact_label', $contact_labelListID)->update(['delete_time' => time()]);
            }
            if (!empty($alreadyCancelledADD)) {
                $alreadyCancelledADD=$this->assoc_unique($alreadyCancelledADD,'content');
                db('order_contact_label_logo', config('database.zong'))->insertAll($alreadyCancelledADD);
            }


            if (!empty($listArrayNew)) {
                db('order_contact_label', config('database.zong'))->insertAll($listArrayNew);
            }
            db()->commit();
            r_date(null, 200);

        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }


    }
    public function OrderContactLabelLogo()
    {
        $data     = Authority::param(['order_id']);
        $telephone = db('order')->where('order_id', $data['order_id'])->value('telephone');
        $logo     = db('order_contact_label_logo', config('database.zong'))->join('order_contact_label','order_contact_label.order_id=order_contact_label_logo.order_id','left')->where('telephone', $telephone)->field('FROM_UNIXTIME(order_contact_label_logo.created_time,"%Y-%m-%d %H:%i:%s") as created_time,CONCAT(CASE order_contact_label_logo.role WHEN 1 THEN "店长"WHEN 2 THEN "客服"WHEN 3 THEN "后台" END ,order_contact_label_logo.operation) as operation,order_contact_label_logo.content')->group('content')->order('created_time desc')->select();
        $tageList = [];
        if (!empty($logo)) {
            foreach ($logo as $k => $v) {
                $result[$v['created_time']][] = $v;
            }
            foreach ($result as $k => $list) {
                $schemeTag['created_time'] = $k;
                $schemeTag['operation']    = $list[0]['operation'];
                $schemeTag['data']         = $result[$k];
                $tageList[]                = $schemeTag;
            }
        }

        r_date($tageList, 200);
    }

    /*
     * 二维数组去重
     */

    public function assoc_unique($arr, $key)
    {
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                unset($arr[$k]);
            } else {
                $tmp_arr[] = $v[$key];
            }
        }
        sort($arr); //sort函数对数组进行排序
        return $arr;
    }

}